package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemo9_3_1 {

	public static void main(String[] args) {
		
		Ticket4 ticket4 = new Ticket4();

		Thread t1 = new Thread(ticket4, "窗口1");
		Thread t2 = new Thread(ticket4, "窗口2");
		Thread t3 = new Thread(ticket4, "窗口3");
		t1.start();
		t2.start();
		t3.start();
	}

}

class Ticket4 implements Runnable {
	private volatile int ticket = 5000;
	
	private volatile int i = 0;
	
	private volatile boolean flag = true;
	
	
	private Lock lock = new ReentrantLock();
	
	//private Object obj = new Object();
	@Override
	public void run() {


		while( flag ){
			//synchronized ( this ) {
			lock.lock();
				try{
					if( this.ticket > 0 ){
						System.out.println( Thread.currentThread().getName() + "准备卖出一张票");
						System.out.println(Thread.currentThread().getName()+ "还有余票:" + ticket);
						
						int a = this.ticket--; // 首先获得this.ticket的值,把它的值减1, 再把减1后的值赋给this.ticket  
						
						System.out.println(Thread.currentThread().getName() + "成功卖出一张票,还有余票" + this.ticket);
					} else {
						break;
					}
				} finally {
					
					lock.unlock();
				}
			//}
		}
	}
	
}
